import 'dart:async';
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:wallet_utils/el_refresh.dart';
import 'package:wallet_utils/event_bus_utils.dart';
import 'package:wallet_utils/location/locationUtil.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/login_utils.dart';
import 'package:wallet_utils/msg_event_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/toast.dart';
import 'package:wallet_utils/webview_common.dart';
import '../../agreement_dialog.dart';
import '../../login_page/constant.dart';
import '../../mine/api/mine_api.dart';
import '../../mine/bean/aboutUsBean.dart';
import '../../mine/bean/productInfoBean.dart';
import '../../mine/contentType.dart';
import '../api/home_api.dart';
import '../api/hxh_url.dart';
import '../bean/popUpsBean.dart';
import '../bean/userAgreementBean.dart';
import '../face_recognition/logic.dart';
import 'general_dialog.dart';
import 'state.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePageLogic extends GetxController {
  final HomePageState state = HomePageState();
  HomeInfo? dataInfo;
  int? authStep = 1; // //1.未认证 2.身份证已认证 3.基本信息已认证 4.联系人信息已认证 5.已申请借款 6.人脸识别
  bool isShowPro = false;
  bool showContacts = false;
  int badgeCount = 0;
  bool isGranted = false;
  bool isShowIncoming=false; //是否有线下api产品
  @override
  Future<void> onInit() async {
    super.onInit();
    state.isLogin= await LoginUtils.isLogin();
    //接收通知刷新接口
    EventBusUtils.getInstance().on<MsgEventBusUtils>().listen((event) async {
      state.isLogin= await LoginUtils.isLogin();
      if (event.type == MsgEventBusUtils.upHomeStatus) {
        state.refreshController = RefreshController(initialRefresh: false);
        obtainIndexInfoV3(state.city);
        getUserInfo(ContentType.personalCredit);
      } else if (event.type == MsgEventBusUtils.popStatus) {
        state.refreshController = RefreshController(initialRefresh: false);
        obtainIndexInfoV3(state.city);
        getUser2Where();
        Future.delayed(const Duration(milliseconds: 500), () {
          if (!event.value) {
            if (state.agreementContent!.isNotEmpty) {
              if (showStatus()) {
                getCpaPopList();
              }
            } else {
              getUser2WhereApi();
            }
            event.value = true;
          }
        });
      }
    });
    LocationUtil().init();
    isGranted = await LocationUtil().request(
        onResult: (Map<String, Object> result) async {
          LogUtils.d("-------------直接取");
          LogUtils.d(result);
          state.city = result['city'].toString();
          obtainIndexInfoV3(state.city);
        },
        isResetLocation: false);
    if (isGranted==false) {
      obtainIndexInfoV3('');
    }

    Future.delayed(const Duration(milliseconds: 1000), () {
      getUser2WhereApi();
    });
    getUserInfo(ContentType.personalCredit);
    // getCpaPopList();
    // obtainAuditResultInfo();
    // showPage();
  }



  void popover(int type, int index, String? agreement) {
    // if(type==5){
    //   jumpFace();
    //
    //   // FaceRecognitionLogic().hxhCheckUser();
    //   return;
    // }
      Future.delayed(Duration.zero, () {
        showDialog<Null>(
          context: Get.context!,
          barrierDismissible: false,
          useSafeArea: false,
          useRootNavigator: false,
          builder: (BuildContext context) {
            return AgreementDialog(
                name: '',
                content: agreement,
                submit: '我已阅读并同意授权',
                isClose: true,
                onTap: () {
                  Get.back();
                  if (type == 1) {
                    if(state.headProductId!=0 ){
                      addLoanRecord(state.headProductId!, ShowPage.home);
                    }
                    Get.to(WebViewCommon(
                      state.headLinkUrl ?? '',
                      title: '',
                    ));
                  } else if (type == 2) {
                    if(state.productList!.isNotEmpty){
                      addLoanRecord(state.productList![index].productId!, ShowPage.home);
                    }
                    Get.to(WebViewCommon(
                      state.productList![index].linkUrl ?? '',
                    ));
                  } else if (type == 3) {
                    if(state.headProductId!=0 ){
                      addLoanRecord(state.headProductId!, ShowPage.home);
                    }
                    Get.to(WebViewCommon(
                      state.headLinkUrl ?? '',
                    ));
                  } else if (type == 4) {
                    if(state.id!=0){
                      addLoanRecord(state.id, ShowPage.home);
                    }
                    Get.to(WebViewCommon(
                      state.popLinkUrl ?? '',
                    ));
                  }else if(type == 5){
                    if(state.bannerList!.isNotEmpty){
                      clickBannerRecord(state.bannerList![0].id!, state.bannerList![0].showPage!);
                    }
                    Get.to(WebViewCommon(
                      state.linkUrl ?? '',
                      title: '',
                    ));
                  }
                });
          },
        );
      });
  }

  //用户隐私协议选中或未选中
  void updateUserPrivary() {
    state.isAgreeUserPrivary = !state.isAgreeUserPrivary;
    update();
  }

  //弹窗
  void getCpaPopList() async {
    HomeApi.getCpaPopList(
        PopUps().homePop,
        BaseCallback(onSuccess: (map) {
          PopUpsBean popUpsBean = PopUpsBean.fromJson(map);
          List<PopUpsInfo>? dataInfo = popUpsBean.data;
          if (dataInfo!.isNotEmpty) {
            state.amount = dataInfo[0].amount;
            state.name = dataInfo[0].name;
            state.popLinkUrl = dataInfo[0].linkUrl;
            state.id = dataInfo[0].id!;
            GeneralDialog(
              amount: state.amount,
              name: state.name,
              popLinkUrl: state.popLinkUrl,
              agreementName: state.agreementName,
              agreementContent: state.agreementContent,
              h5Callback: () {
                // getUserInfo(ContentType.personalCredit);
              },
            ).showGeneralFunction(Get.context);
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  //查询用户状态 用于首页UI配置
  void obtainIndexInfoV3(String cityName) async {
    HomeApi.obtainIndexInfoV3(
        cityName,
        BaseCallback(onSuccess: (map) {
          ProductInfoBean productInfoBean = ProductInfoBean.fromJson(map);
          if (productInfoBean.data != null) {
            dataInfo = productInfoBean.data;
            state.noticeMsg = dataInfo?.noticeMsg;
            state.bannerList = dataInfo!.bannerList;
            state.indexStatus = dataInfo?.indexStatus;
            LoginUtils.setIndexStatus(state.indexStatus!.toInt());
            isShowIncoming = dataInfo!.isShowIncoming!;
            state.isShowChannelAuth = dataInfo?.isShowChannelAuth;
            if (state.bannerList!.isNotEmpty) {
              state.imgUrl = state.bannerList![0].imgUrl;
              state.linkUrl = state.bannerList![0].linkUrl;
            }
            // if (state.indexStatus != 1) {
              EventBusUtils.getInstance().fire(
                MsgEventBusUtils(MsgEventBusUtils.upMineStatus),
              );
            // }
            num? showListProductFlag = productInfoBean.data?.showListProductFlag;
            EventBusUtils.getInstance().fire(
              MsgEventBusUtils(MsgEventBusUtils.productStatus, value: showListProductFlag, status: state.indexStatus),
            );
            state.defaultProductVO = dataInfo?.defaultProductVO;
            state.loanRemind = dataInfo?.loanRemind;
            state.showProductFlag = productInfoBean.data?.showProductFlag;
            indexStatus();
            checkAuthStep();
            if (dataInfo!.productList != null) {
              state.productList = dataInfo?.productList;
              state.headProductName=state.productList![0].productName;
              state.headLoanAmount=state.productList![0].loanAmount;
              state.headLoanMinRate=state.productList![0].loanMinRate;
              state.headLoanPeriod=state.productList![0].loanPeriod;
              state.headLinkUrl=state.productList![0].linkUrl;
              state.headProductId=state.productList![0].productId;
            }
          }
          refreshCompelet(state.refreshController);
          // state.refreshController.refreshCompleted();
          update();
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            // state.refreshController.refreshCompleted();
            refreshCompelet(state.refreshController);
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  void indexStatus() {
    if (!isShowIncoming && state.showProductFlag==1) {
      state.homeTitle = '您的预估额度(元)';
      state.homeBtn = '立即提现';
      return;
    }
    switch (state.indexStatus) {
      case 1:
        //未认证
        state.homeTitle = '资料审核通过，最高可借(元)';
        state.homeContent = '恭喜您已通过预审，完善资料系统将为您推送产品';
        state.homeBtn = '立即完善资料';
        break;

      case 3:
        //审核中
        state.homeTitle = '您的预估额度(元)';
        state.homeBtn = '立即提现';
        break;
      case 4:
        //审核拒绝
        state.homeTitle = '您的预估额度(元)';
        state.homeBtn = '立即提现';
        break;
      case 6:
        //待还款

        break;
      default:
        state.homeTitle = '完善资料最高可获(元)';
        state.homeContent = '恭喜您已通过预审，完善资料立即提现';
        state.homeBtn = '立即完善资料';
        break;
    }
  }

  bool showStatus() {
    bool isShow = false;
    if (state.indexStatus == 3 || state.indexStatus == 4) {
      isShow = true;
    }
    return isShow;
  }

  bool isShowStatus() {
    bool isShow = false;
    if (state.indexStatus == 3 || state.indexStatus == 4) {
      isShow = true;
    }else{
      if (!isShowIncoming && state.showProductFlag==1) {
        return true;
      }
    }
    return isShow;
  }

  bool homeHead() {
    bool isShow = false;
    if(!isShowIncoming && state.showProductFlag==2){
      return false;
    }
    if (state.indexStatus == 6) {
      if (state.showProductFlag == 2) {
        isShow = true;
      } else {
        isShow = false;
      }
    } else if (state.indexStatus == 3 || state.indexStatus == 4) {
      if (state.showProductFlag == 2) {
        isShow = false;
      } else {
        isShow = true;
      }
    } else {
      isShow = true;
    }

    return isShow;
  }

  bool isShowBanner() {
    bool isShow = false;
    if (state.bannerList!.isEmpty || state.showProductFlag != 1) {
      isShow = false;
    } else {
      isShow = true;
    }
    return isShow;
  }

  //首页金刚区
  void showPage() async {
    HomeApi.showPage(
        Constant().home,
        BaseCallback(
            onSuccess: (map) {},
            onError: (msg) {
              Future.delayed(const Duration(milliseconds: 500), () {
                ToastUtils.showToast(msg ?? "");
              });
            }));
  }

  //获取用户审核结果
  void obtainAuditResultInfo() async {
    HomeApi.obtainAuditResultInfo(BaseCallback(
        onSuccess: (map) {},
        onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  //获取用户认证步骤
  void checkAuthStep() async {
    HomeApi.checkAuthStep(BaseCallback(onSuccess: (map) {
      //1.未认证 2.身份证已认证 3.基本信息已认证 4.联系人信息已认证 5.已申请借款 6.人脸识别
      authStep = map['data']['authStep'];
      isShowProgress();
      update();
      LogUtils.d('用户认证步骤 $authStep');
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }

  void isShowProgress() {
    if (!isShowIncoming) {
      isShowPro = false;
      return;
    }
    showContact();
    switch (authStep) {
      case 1:
        isShowPro = false;
        break;
      case 2:
        isShowPro = true;
        if (dataInfo?.isShowFace == 1) {
          if (showContacts) {
            badgeCount = dataInfo?.channelAuthType == 1 ? 30 : 60;
          } else {
            badgeCount = dataInfo?.channelAuthType == 1 ? 50 : 90;
          }
        } else {
          if (showContacts) {
            badgeCount = dataInfo?.channelAuthType == 1 ? 50 : 90;
          } else {
            badgeCount = dataInfo?.channelAuthType == 1 ? 50 : 100;
          }
        }
        break;
      case 3:
        if (state.isShowChannelAuth == 0) {
          if (dataInfo?.isShowFace == 1) {
            isShowPro = true;
            if (showContacts) {
              badgeCount = 50;
            } else {
              badgeCount = 50;
            }
          } else {
            if (showContacts) {
              isShowPro = true;
              badgeCount = 50;
            } else {
              badgeCount = 100;
              isShowPro = false;
            }
          }
        } else {
          isShowPro = true;
          if (dataInfo?.isShowFace == 1) {
            if (showContacts) {
              badgeCount = dataInfo?.channelAuthType == 1 ? 60 : 30;
            } else {
              badgeCount = dataInfo?.channelAuthType == 1 ? 90 : 40;
            }
          } else {
            if (showContacts) {
              badgeCount = dataInfo?.channelAuthType == 1 ? 90 : 40;
            } else {
              badgeCount = dataInfo?.channelAuthType == 1 ? 100 : 50;
            }
          }
        }
        break;
      case 4:
        if (dataInfo?.isShowFace == 1) {
          isShowPro = true;
          badgeCount = 90;
        } else {
          isShowPro = false;
          badgeCount = 100;
        }
        break;
      case 5:
        isShowPro = false;
        break;
      case 6:
        isShowPro = false;
        break;
    }
  }

  void showContact() {
    if (dataInfo?.isShowCommonLiaison == 1 || dataInfo?.isShowUrgentLiaison == 1 || dataInfo?.isShowProfession == 1) {
      showContacts = true;
    } else {
      showContacts = false;
    }
  }

  Future<void> jumpPage() async {
    if (!isShowIncoming) {
      if(state.productList!.isNotEmpty){
        popover(1, 0, state.content);
      }
      return;
    }
    if (state.isShowChannelAuth == 0) {
      if (authStep == 1) {
        //基本信息
        Get.toNamed(BaseRouterConfig.basicInfo, arguments: {
          'face': dataInfo?.isShowFace,
          'showContacts': showContacts,
          'isShowIdCard': state.isShowChannelAuth,
          'channelAuthType': dataInfo?.channelAuthType
        });
      } else if (authStep == 3 && showContacts) {
        //联系人
        Get.toNamed(BaseRouterConfig.contactPerson, arguments: {
          'isShowIncoming': false,
          'face': dataInfo?.isShowFace,
          'isShowIdCard': state.isShowChannelAuth,
          'channelAuthType': dataInfo?.channelAuthType,
        });
      } else {
        //人脸识别
        if (showStatus()) {
          if(state.productList!.isNotEmpty) {
            popover(1, 0, state.agreementContent);
          }
        } else {
          if (dataInfo?.isShowFace == 1) {
            await jumpFace();
          }
        }
      }
    } else {
      if (dataInfo?.channelAuthType == 1) {
        if (authStep == 1) {
          //身份认证
          Get.toNamed(BaseRouterConfig.identityCertification, arguments: {
            'isShowIncoming': false,
            'face': dataInfo?.isShowFace,
            'showContacts': showContacts,
            'isShowIdCard': state.isShowChannelAuth,
            'channelAuthType': dataInfo?.channelAuthType
          });
        } else if (authStep == 2) {
          //基本信息
          Get.toNamed(BaseRouterConfig.basicInfo, arguments: {
            'face': dataInfo?.isShowFace,
            'showContacts': showContacts,
            'isShowIdCard': state.isShowChannelAuth,
            'channelAuthType': dataInfo?.channelAuthType
          });
        } else if (authStep == 3 && showContacts) {
          //联系人
          Get.toNamed(BaseRouterConfig.contactPerson, arguments: {
            'isShowIncoming': false,
            'face': dataInfo?.isShowFace,
            'isShowIdCard': state.isShowChannelAuth,
            'channelAuthType': dataInfo?.channelAuthType,
          });
        } else {
          //人脸识别
          if (showStatus()) {
            if(state.productList!.isNotEmpty) {
              popover(1, 0, state.agreementContent);
            }
          } else {
            if (dataInfo?.isShowFace == 1) {
              await jumpFace();
            }
          }
        }
      } else {
        if (authStep == 1) {
          //基本信息
          Get.toNamed(BaseRouterConfig.basicInfo, arguments: {
            'face': dataInfo?.isShowFace,
            'showContacts': showContacts,
            'isShowIdCard': state.isShowChannelAuth,
            'channelAuthType': dataInfo?.channelAuthType
          });
        } else if (authStep == 2 && showContacts) {
          //联系人
          Get.toNamed(BaseRouterConfig.contactPerson, arguments: {
            'isShowIncoming': false,
            'face': dataInfo?.isShowFace,
            'isShowIdCard': state.isShowChannelAuth,
            'channelAuthType': dataInfo?.channelAuthType,
          });
        } else if (authStep == 3) {
          //身份认证
          Get.toNamed(BaseRouterConfig.identityCertification, arguments: {
            'isShowIncoming': false,
            'face': dataInfo?.isShowFace,
            'showContacts': showContacts,
            'isShowIdCard': state.isShowChannelAuth,
            'channelAuthType': dataInfo?.channelAuthType
          });
        } else {
          //人脸识别
          if (showStatus()) {
            if(state.productList!.isNotEmpty) {
              popover(1, 0, state.agreementContent);
            }
          } else {
            if (dataInfo?.isShowFace == 1) {
              await jumpFace();
            }
          }
        }
      }
    }
  }

  Future<void> jumpFace() async {
    WidgetsFlutterBinding.ensureInitialized();
    state.cameras = await availableCameras();

    /// 获取设备摄像头，默认0:后置 1:前置
    state.firstCamera = state.cameras!.first;
    Get.toNamed(BaseRouterConfig.faceRecognition, arguments: {
      'isShowIncoming': false,
      'camera': state.cameras,
    });
  }

  //埋点
  void addLoanRecord(num productId, int showPage) async {
    HomeApi.addLoanRecord(
        productId,
        showPage,
        BaseCallback(
            onSuccess: (map) {},
            onError: (msg) {
              Future.delayed(const Duration(milliseconds: 500), () {
                ToastUtils.showToast(msg ?? "");
              });
            }));
  }

  //banner埋点
  void clickBannerRecord(num bannerId, num showPage) async {
    HomeApi.clickBannerRecord(
        bannerId,
        showPage,
        BaseCallback(
            onSuccess: (map) {},
            onError: (msg) {
              Future.delayed(const Duration(milliseconds: 500), () {
                ToastUtils.showToast(msg ?? "");
              });
            }));
  }

  void homeProductJump(int index) {
    if (state.indexStatus == 3 || state.indexStatus == 4) {
      popover(2, index, state.agreementContent);
    } else {
      popover(2, index, state.content);
    }
  }

  jumpH5Page(String name) {
    switch (name) {
      case '我要还款':
        popover(3, 0, state.content);
        break;
      case 'banner':
        if (state.indexStatus == 3 || state.indexStatus == 4) {
          popover(5, 0, state.agreementContent);
        } else {
          popover(5, 0, state.content);
        }
        break;
      case '去提现':
        popover(4, 0, state.agreementContent);
        break;
    }
  }

  //信用授权书
  getUserInfo(int type) {
    MineApi.getHTML(
        type,
        BaseCallback(onSuccess: (map) {
          AboutUsBean aboutUsBean = AboutUsBean.fromJson(map);
          if (aboutUsBean.data != null) {
            // state.agreementName = aboutUsBean.data?.name;
            state.content = aboutUsBean.data?.content;
            // Get.toNamed(BaseRouterConfig.agreement, arguments: {'name': name, 'content': content});
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  void getUser2WhereApi() async {
    HomeApi.getUser2WhereApi(BaseCallback(onSuccess: (map) {
      UserAgreementBean userAgreementBean = UserAgreementBean.fromJson(map);
      if (userAgreementBean.data != null) {
        state.agreementContent = userAgreementBean.data?.content;
        if (showStatus()) {
          getCpaPopList();
        }
        update();
      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }

  void getUser2Where() async {
    HomeApi.getUser2WhereApi(BaseCallback(onSuccess: (map) {
      UserAgreementBean userAgreementBean = UserAgreementBean.fromJson(map);
      if (userAgreementBean.data != null) {
        state.agreementContent = userAgreementBean.data?.content;
        update();
      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }


}
